package org.sdnstproject.interlayer.OF13Protocal;

import java.util.HashMap;
import java.util.Random;

import org.projectfloodlight.openflow.types.U16;
import org.projectfloodlight.openflow.types.U32;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

public class FuMeterMod {
	private static final Logger log = LoggerFactory.getLogger(FuMeterMod.class);
    public byte version = 4;
    public byte type = 29;
    public short length = 16;//MINIMUM_LENGTH = 16;
    public long xid = 0x0L;
    public int command = 0x0;//TODO
    public int flags = 0x0;//TODO
    public long meterId = 0x0L;//TODO
    public byte[] meters = new byte[] {};
    
    public FuMeterMod() {
    	
    }
    
    public FuMeterMod setField(String field, String value) {
		switch (field) {
		case "version":
			this.version = Byte.parseByte(value);
			break;
		case "type":
			this.type = Byte.parseByte(value);
			break;
		case "length":
			this.length = Short.parseShort(value);
			break;
		case "xid":
			this.xid = Long.parseLong(value);
			break;
		case "command":
			this.command = Integer.parseInt(value);
			break;
		case "flags":
			this.flags = Integer.parseInt(value);
			break;
		case "meterId":
			this.meterId = Long.parseLong(value);
			break;
		case "meters":
			this.meters = new byte[new Random().nextInt(60)];//TODO
			new Random().nextBytes(meters);
			break;
		}
		return this;
	}
    
    public ByteBuf writeTo() {
    	ByteBuf bb = Unpooled.directBuffer();
    	int startIndex = bb.writerIndex();
        // fixed value property version = 4
        bb.writeByte(version);
        // fixed value property type = 29
        bb.writeByte(type);
        // length is length of variable message, will be updated at the end
        int lengthIndex = bb.writerIndex();
        bb.writeShort(length);

        bb.writeInt(U32.t(xid));
        bb.writeShort(U16.t(command));
        bb.writeShort(U16.t(flags));
        bb.writeInt(U32.t(meterId));
        bb.writeBytes(meters);

        // update length field
        int length = bb.writerIndex() - startIndex;
        bb.setShort(lengthIndex, length);
        return bb;
    }
    
    @Override
    public String toString() {
        StringBuilder b = new StringBuilder("OFMeterModVer13(");
        b.append("version=").append(version);
        b.append(", ");
        b.append("type=").append(type);
        b.append(", ");
        b.append("length=").append(length);
        b.append(", ");
        b.append("xid=").append(xid);
        b.append(",");
        b.append("command=").append(command);
        b.append(", ");
        b.append("flags=").append(flags);
        b.append(", ");
        b.append("meterId=").append(meterId);
        b.append(", ");
        b.append("meters=").append(meters);
        b.append(")");
        return b.toString();
    }
}
